<template>
  <a-button type="primary" @click="handleUpload" :class="buttonClass">
    <template #icon>
      <icon-upload />
    </template>
    <template #default>{{ buttonText }}</template>
  </a-button>
</template>

<script lang="ts" setup>
import { inject, watch } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  buttonText: {
    type: String,
    default: '点击上传'
  },
  buttonClass: {
    type: String,
    default: 'fit-content'
  }
})

const emit = defineEmits(['update:modelValue']);

// 注入祖先组件提供的函数
const handleUploadFromAncestor = inject<((flag: boolean, name: string) => void)>('handleUpload', () => {});
const fileUrl = inject<any>('fileUrl', null);
const chooseName = inject<any>('chooseName', null);

const handleUpload = () => {
  if (!handleUploadFromAncestor) {
    console.warn('Upload: handleUpload function not provided by ancestor');
    return;
  }
  handleUploadFromAncestor(true, props.name);
}

// 监听文件上传结果
watch(
  () => [fileUrl?.value, chooseName?.value],
  ([newFileUrl, newChooseName]: [string | null | undefined, string | null | undefined]) => {
    // 只有当 chooseName 匹配当前组件的 name 时才更新
    if (!newFileUrl || !newChooseName || newChooseName !== props.name) {
      return;
    }

    emit('update:modelValue', newFileUrl);
  },
  { immediate: false }
)
</script>

<style scoped>
.fit-content {
  width: fit-content;
}
</style>